//
//  SIUtil.m
//  CampingLight
//
//  Created by Piccolo on 2017/11/5.
//  Copyright © 2017年 SmartIT. All rights reserved.
//

#import "SIUtil.h"
#import <sys/sysctl.h>
#import "SICPSDKService.h"
#import "NSUserDefaults+RMSaveCustomObject.h"

#define kIgnoreSetting -1

@implementation SIUtil

+ (NSString *)getSingleKeyStr:(NSString *)str{
    return NSLocalizedString(str, nil);
}

+ (NSString *)getDoubleKeyStr:(NSString *)str1 secondKey:(NSString *)str2{
    NSString *infoStr = [NSString stringWithFormat:@"%@%@", [self getSingleKeyStr:str1], [self getSingleKeyStr:str2]];
    return infoStr;
}

+ (NSString *)getTripleKeyStr:(NSString *)str1 secondKey:(NSString *)str2 thirdKey:(NSString *)str3{
    NSString *infoStr = [NSString stringWithFormat:@"%@%@", [self getDoubleKeyStr:str1 secondKey:str2], [self getSingleKeyStr:str3]];
    return infoStr;
}

+ (NSString *)removeSpace:(NSString *)str{
    return  [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

+ (NSString *)platformString
{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    free(machine);
    
    // Created from this thread: https://gist.github.com/Jaybles/1323251
    
    // Apple TV
    if ([platform isEqualToString:@"AppleTV2,1"])   return @"Apple TV 2G";
    if ([platform isEqualToString:@"AppleTV3,1"])   return @"Apple TV 3G";
    if ([platform isEqualToString:@"AppleTV3,2"])   return @"Apple TV 3G";
    if ([platform isEqualToString:@"AppleTV5,3"])   return @"Apple TV 4G";
    
    // Apple Watch
    if ([platform isEqualToString:@"Watch1,1"])     return @"Apple Watch";
    if ([platform isEqualToString:@"Watch1,2"])     return @"Apple Watch";
    
    // iPhone
    if ([platform isEqualToString:@"iPhone1,1"])    return @"iPhone 2G";
    if ([platform isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"])    return @"iPhone 4 (GSM)";
    if ([platform isEqualToString:@"iPhone3,2"])    return @"iPhone 4 (GSM/2012)";
    if ([platform isEqualToString:@"iPhone3,3"])    return @"iPhone 4 (CDMA)";
    if ([platform isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"])    return @"iPhone 5 (GSM)";
    if ([platform isEqualToString:@"iPhone5,2"])    return @"iPhone 5 (Global)";
    if ([platform isEqualToString:@"iPhone5,3"])    return @"iPhone 5c (GSM)";
    if ([platform isEqualToString:@"iPhone5,4"])    return @"iPhone 5c (Global)";
    if ([platform isEqualToString:@"iPhone6,1"])    return @"iPhone 5s (GSM)";
    if ([platform isEqualToString:@"iPhone6,2"])    return @"iPhone 5s (Global)";
    if ([platform isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([platform isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([platform isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([platform isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    if ([platform isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
    if ([platform isEqualToString:@"iPhone9,1"])    return @"iPhone 7 (Global)";
    if ([platform isEqualToString:@"iPhone9,2"])    return @"iPhone 7 Plus (Global)";
    if ([platform isEqualToString:@"iPhone9,3"])    return @"iPhone 7 (GSM)";
    if ([platform isEqualToString:@"iPhone9,4"])    return @"iPhone 7 Plus (GSM)";
    if ([platform isEqualToString:@"iPhone10,1"])    return @"iPhone 8 (CDMA)";
    if ([platform isEqualToString:@"iPhone10,2"])    return @"iPhone 8 Plus (CDMA)";
    if ([platform isEqualToString:@"iPhone10,3"])    return @"iPhone X (CDMA)";
    if ([platform isEqualToString:@"iPhone10,4"])    return @"iPhone 8 (GSM)";
    if ([platform isEqualToString:@"iPhone10,5"])    return @"iPhone 8 Plus (GSM)";
    if ([platform isEqualToString:@"iPhone10,6"])    return @"iPhone X (GSM)";
    
    // iPad
    if ([platform isEqualToString:@"iPad1,1"])      return @"iPad 1";
    if ([platform isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([platform isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([platform isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([platform isEqualToString:@"iPad2,4"])      return @"iPad 2 (Mid 2012)";
    if ([platform isEqualToString:@"iPad3,1"])      return @"iPad 3 (WiFi)";
    if ([platform isEqualToString:@"iPad3,2"])      return @"iPad 3 (CDMA)";
    if ([platform isEqualToString:@"iPad3,3"])      return @"iPad 3 (GSM)";
    if ([platform isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([platform isEqualToString:@"iPad3,5"])      return @"iPad 4 (GSM)";
    if ([platform isEqualToString:@"iPad3,6"])      return @"iPad 4 (Global)";
    
    // iPad Air
    if ([platform isEqualToString:@"iPad4,1"])      return @"iPad Air (WiFi)";
    if ([platform isEqualToString:@"iPad4,2"])      return @"iPad Air (Cellular)";
    if ([platform isEqualToString:@"iPad4,3"])      return @"iPad Air (China)";
    if ([platform isEqualToString:@"iPad5,3"])      return @"iPad Air 2 (WiFi)";
    if ([platform isEqualToString:@"iPad5,4"])      return @"iPad Air 2 (Cellular)";
    
    // iPad Mini
    if ([platform isEqualToString:@"iPad2,5"])      return @"iPad Mini (WiFi)";
    if ([platform isEqualToString:@"iPad2,6"])      return @"iPad Mini (GSM)";
    if ([platform isEqualToString:@"iPad2,7"])      return @"iPad Mini (Global)";
    if ([platform isEqualToString:@"iPad4,4"])      return @"iPad Mini 2 (WiFi)";
    if ([platform isEqualToString:@"iPad4,5"])      return @"iPad Mini 2 (Cellular)";
    if ([platform isEqualToString:@"iPad4,6"])      return @"iPad Mini 2 (China)";
    if ([platform isEqualToString:@"iPad4,7"])      return @"iPad Mini 3 (WiFi)";
    if ([platform isEqualToString:@"iPad4,8"])      return @"iPad Mini 3 (Cellular)";
    if ([platform isEqualToString:@"iPad4,9"])      return @"iPad Mini 3 (China)";
    if ([platform isEqualToString:@"iPad5,1"])      return @"iPad Mini 4 (WiFi)";
    if ([platform isEqualToString:@"iPad5,2"])      return @"iPad Mini 4 (Cellular)";
    
    // iPad Pro
    if ([platform isEqualToString:@"iPad6,3"])      return @"iPad Pro (9.7 inch/WiFi)";
    if ([platform isEqualToString:@"iPad6,4"])      return @"iPad Pro (9.7 inch/Cellular)";
    if ([platform isEqualToString:@"iPad6,7"])      return @"iPad Pro (12.9 inch/WiFi)";
    if ([platform isEqualToString:@"iPad6,8"])      return @"iPad Pro (12.9 inch/Cellular)";
    
    // iPod
    if ([platform isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([platform isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([platform isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([platform isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([platform isEqualToString:@"iPod5,1"])      return @"iPod Touch 5G";
    if ([platform isEqualToString:@"iPod7,1"])      return @"iPod Touch 6G";
    
    // Simulator
    if ([platform isEqualToString:@"i386"])         return @"Simulator";
    if ([platform isEqualToString:@"x86_64"])       return @"Simulator";
    
    return platform;
}

+ (BOOL)delegateExist:(id)delegate delegate:(Protocol *)protocol selector:(SEL)aSelector{
    BOOL bool1 = delegate;
    BOOL bool2 = [delegate conformsToProtocol:protocol];
    BOOL bool3 = [delegate respondsToSelector:aSelector];
    
    NSLog(@"@221%d%d%d",bool1, bool2, bool3);
    return delegate && [delegate conformsToProtocol:protocol] && [delegate respondsToSelector:aSelector];
}

+ (UIBarButtonItem *)newBarItemWithImageName:(NSString *)imageName target:(UIViewController *)vc action:(SEL)action {
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self removeBtnTarget:btn];
    [btn addTarget:vc action:action forControlEvents:UIControlEventTouchUpInside];
    btn.frame = CGRectMake(0, 0, 25.f, 25.f);
    btn.imageEdgeInsets = UIEdgeInsetsMake(-2, -2, -2, -2);
    [btn setHitTestEdgeInsets:UIEdgeInsetsMake(-15.f, -15.f, -15.f, -15.f)];
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [self adaptNavigationBarItemLayout:btn size:NAVIGATION_BAR_ITEM_SIZE];
    UIBarButtonItem* buttonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    return buttonItem;
}

+ (void)setBtn:(UIButton *)btn imageName:(NSString *)imageName {
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    btn.titleEdgeInsets = UIEdgeInsetsMake(-5, -5, -5, -5);

}

+ (void)setViewRoundCorner:(UIView *)view {
    view.layer.borderWidth = 1.f;
    view.layer.borderColor = [UIColor whiteColor].CGColor;
    view.layer.cornerRadius = CGRectGetHeight(view.frame) / 2.f;
    view.clipsToBounds = YES;
}

+ (void)removeBtnTarget:(UIButton *)btn {
    [btn removeTarget:nil
               action:NULL
     forControlEvents:UIControlEventAllEvents];
}

+ (void)addBtn:(UIButton *)btn target:(UIViewController *)target action:(SEL)action {
    [self removeBtnTarget:btn];
    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
}

+ (void)setBtn:(UIButton *)btn imageName:(NSString *)imageName needRoundCorner:(BOOL)needRoundCorner target:(UIViewController *)target action:(SEL)action {
    if (imageName) {
        [self setBtn:btn imageName:imageName];
    }
    if (needRoundCorner) {
        [self setViewRoundCorner:btn];
    }
    if (target && action) {
        [self addBtn:btn target:target action:action];
    }
}

+ (void)setBtn:(UIButton *)btn imageName:(NSString *)imageName title:(NSString *)title target:(UIViewController *)target action:(SEL)action {
    if (imageName) {
        [btn setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    }
    if (title) {
        [btn setTitle:title forState:UIControlStateNormal];
    }
    if (target && action) {
        [self addBtn:btn target:target action:action];
    }
}

+ (void)adaptNavigationBarItemLayout:(UIView *)view size:(CGSize)size {
    
    if ([[SIUtil getDeviceVersion] floatValue] < 11) {
        view.frame = CGRectMake(0, 0, size.width, size.height);
    } else {
        NSLayoutConstraint * widthConstraint = [view.widthAnchor constraintEqualToConstant:size.width];
        NSLayoutConstraint * heightConstraint =[view.heightAnchor constraintEqualToConstant:size.height];
        [widthConstraint setActive:YES];
        [heightConstraint setActive:YES];
    }
}

+ (NSString *)getDeviceVersion {
    return [[UIDevice currentDevice] systemVersion];
}

+ (void)setShadowToView:(UIView *)view {
    view.layer.masksToBounds = NO;
    //    RGB_UICOLOR(222, 222, 222)
    view.layer.shadowColor = RGB_UICOLOR(222, 222, 222).CGColor;
    view.layer.shadowOffset = CGSizeMake(0, 0);
    view.layer.shadowRadius = 5;
    view.layer.shadowOpacity = 0.5;
    view.layer.cornerRadius = 6.f;
}


+ (BOOL)checkString:(NSString *)parentStr containSubString:(NSString *)subStr{

    NSString *trimmingSubStr = [subStr stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSLog(@"@243:parent:%@ sub:%@", parentStr, trimmingSubStr);
    return [parentStr rangeOfString:trimmingSubStr].location != NSNotFound;
}


+ (BOOL)checkPlatformIsFourType{
    return [self checkString:[self platformString] containSubString:@"iPhone 4"];
}

+ (BOOL)checkPlatformIsFiveType{
    return [self checkString:[self platformString] containSubString:@"iPhone 5"];
}

+ (BOOL)checkPlatformIsSixType{
    BOOL bool1 = [[self platformString] isEqualToString:@"iPhone 6"];
    BOOL bool2 = [[self platformString] isEqualToString:@"iPhone 6s"];
    BOOL bool3 = [[self platformString] isEqualToString:@"iPhone SE"];
    BOOL bool4 = [[self platformString] isEqualToString:@"iPhone 7 (Global)"];
    BOOL bool5 = [[self platformString] isEqualToString:@"iPhone 7 (GSM)"];
    return bool1 || bool2 || bool3 || bool5 || bool4;
}

+ (BOOL)checkPlatformIsSixPlusType{
    BOOL bool1 = [[self platformString] isEqualToString:@"iPhone 6 Plus"];
    BOOL bool2 = [[self platformString] isEqualToString:@"iPhone 6s Plus"];
    BOOL bool4 = [[self platformString] isEqualToString:@"iPhone 7 Plus (Global)"];
    BOOL bool5 = [[self platformString] isEqualToString:@"iPhone 7 Plus (GSM)"];
    return bool1 || bool2 || bool4 || bool5;
}

+ (void)setCustomView:(UIView *)view transformMakeWidth:(CGFloat)width height:(CGFloat)height{
    if ([self checkPlatformIsFiveType] || [self checkPlatformIsFourType]) {
        view.transform = CGAffineTransformMakeScale(width, height);
    }
    view.transform = CGAffineTransformMakeScale(width, height);
}

+ (void)resetView:(UIView *)view xValue:(CGFloat)xValue yValue:(CGFloat)yValue width:(CGFloat)width height:(CGFloat)height {
    CGRect viewFrame = view.frame;
    viewFrame = CGRectMake(xValue ? xValue : CGRectGetMinX(viewFrame), yValue ? yValue : CGRectGetMinY(viewFrame), width ? width : CGRectGetWidth(viewFrame), height ? height : CGRectGetHeight(viewFrame));
    view.frame = viewFrame;
}

+ (void)resetView:(UIView *)view deltaX:(CGFloat)deltaX deltaY:(CGFloat)deltaY deltaWidth:(CGFloat)deltaWidth deltaHeight:(CGFloat)deltaHeight {
    CGRect viewFrame = view.frame;
    viewFrame = CGRectMake(CGRectGetMinX(viewFrame) + deltaX, CGRectGetMinY(viewFrame) + deltaY, CGRectGetWidth(viewFrame) + deltaWidth, CGRectGetHeight(viewFrame) + deltaHeight);
    view.frame = viewFrame;
}

+ (void)setIndicator:(DGActivityIndicatorView *) indicator hidden:(BOOL)hidden target:(UIViewController *)target aboveSubView:(UIView *)view{
    [self setIndicator:indicator hidden:hidden target:target aboveSubView:view showBlackView:NO];
}

+ (void)setIndicator:(DGActivityIndicatorView *) indicator hidden:(BOOL)hidden target:(UIViewController *)target aboveSubView:(UIView *)view showBlackView:(BOOL)showBlackView{
    
    [self doAtMainThreadOfAction:^{
        if (hidden) {
            [indicator removeFromSuperview];
        }else{
            indicator.hidden = NO;
            if (![target.view.subviews containsObject:indicator]) {
                if (view) {
                    [target.view insertSubview:indicator aboveSubview:view];
                }else{
                    [target.view addSubview:indicator];
                }
            }
        }
        if (showBlackView) {
            for (UIView *subView in target.view.subviews) {
                if (subView.tag == 6729374) {
                    return;
                }
            }
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
            view.backgroundColor = [UIColor blackColor];
            view.alpha = .5f;
            view.tag = 6729374;
            [target.view addSubview:view];
            
        } else {
            for (UIView *subView in target.view.subviews) {
                if (subView.tag == 6729374) {
                    [subView removeFromSuperview];
                }
            }
        }
        target.navigationItem.hidesBackButton = showBlackView;
    }];
    
}

+ (void)doAtMainThreadOfAction:(void(^)(void))action {
    
    if (action) {
        if (strcmp(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL), dispatch_queue_get_label(dispatch_get_main_queue())) == 0) {
            // do something  in main thread
            action();
        } else {
            // do something in other thread
            dispatch_async(dispatch_get_main_queue(), ^{
                action();
            });
        }
    }
}


+ (DGActivityIndicatorView *)newIndicatorWithTarget:(UIViewController *)vc centerPoint:(CGPoint)point{
    DGActivityIndicatorView *indicator = [[DGActivityIndicatorView alloc] initWithType:DGActivityIndicatorAnimationTypeLineScale tintColor:[UIColor whiteColor]];
    indicator.frame = CGRectMake(0, 0, 20.f, 20.f);
    indicator.center = point;
    [indicator startAnimating];
    indicator.alpha = 1.f;
    indicator.transform = CGAffineTransformMakeScale(1.f, .7f);
    
    return indicator;
}

+ (BOOL)checkStringExist:(NSString *)str {
    if (!str) {
        return NO;
    } else if ([str isEqualToString:@""]) {
        return NO;
    } else {
        return YES;
    }
}


+ (BOOL)isExistDic:(NSDictionary *)dic key:(NSString *)key{
    //    return [dic.allKeys containsObject:key] && dic[key] != [NSNull null] && [dic[key] count] > 0;
    if ([dic.allKeys containsObject:key]) {
        if (dic[key] != [NSNull null]){
            if ([dic[key] isKindOfClass:[NSArray class]]) {
                return [dic[key] count];
            }
            else{
                return YES;
            }
        }
        else{
            return NO;
        }
    }
    else{
        return NO;
    }
}


+ (void)setCampingLightInfo:(SILightInfo *)lightInfo
                       mode:(NSSILightMode)mode {
    if (mode != kIgnoreSetting) {
        lightInfo.mode = mode;
    }
}

+ (void)setCampingLightInfo:(SILightInfo *)lightInfo
            brightnessValue:(NSInteger)brightnessValue
             colorTempValue:(NSInteger)colorTempValue {
    
    if (brightnessValue != kIgnoreSetting && colorTempValue != kIgnoreSetting) {
        lightInfo.brightnessValue = brightnessValue;
        lightInfo.colorTempValue = colorTempValue;
        if ((brightnessValue || colorTempValue) && lightInfo.mode == NSSILightModeOff) {
            lightInfo.mode = NSSILightModeDimming;
        }
    }
}

+ (void)setCampingLightInfo:(SILightInfo *)lightInfo smartTimeHour:(NSUInteger)smartTimeHour smartTimeMinute:(NSUInteger)smartTimeMinute {
    
    lightInfo.lightTimeInfo.smartTimeHour = smartTimeHour;
    lightInfo.lightTimeInfo.smartTimeMinute = smartTimeMinute;
}

+ (NSDate *)awakenOnTimeFromCampingLightInfo:(SILightInfo *)lightInfo {
    return [SIUtil dateFromHour:lightInfo.lightTimeInfo.awakenOnTimeHour minute:lightInfo.lightTimeInfo.awakenOnTimeMinute];
}

+ (NSDate *)awakenOffTimeFromCampingLightInfo:(SILightInfo *)lightInfo {
    return [SIUtil dateFromHour:lightInfo.lightTimeInfo.awakenOffTimeHour minute:lightInfo.lightTimeInfo.awakenOffTimeMinute];
}

+ (void)setDownView:(UIView *)downView aboveView:(UIView *)upView spacing:(CGFloat)spacing {
    CGRect downViewFrame = downView.frame;
    CGRect upViewFrame = upView.frame;
    downViewFrame.origin.y = CGRectGetMaxY(upViewFrame) + spacing;
    downView.frame = downViewFrame;
}

+ (void)setRightView:(UIView *)rightView nextToView:(UIView *)leftView sameFrame:(BOOL)sameFrame spacing:(CGFloat)spacing {
    
    CGRect rightViewFrame = rightView.frame;
    CGRect leftViewFrame = leftView.frame;
    if (sameFrame) {
        rightViewFrame = leftViewFrame;
    }
    rightViewFrame.origin.x = CGRectGetMaxX(leftViewFrame) + spacing;
    rightView.frame = rightViewFrame;
}

+ (void)setBtn:(UIButton *)btn enabled:(BOOL)enabled {
    btn.enabled = enabled;
    btn.layer.borderColor = enabled ? [UIColor whiteColor].CGColor : DISENABLED_BORDER_COLOR.CGColor;
}

+ (void)setBtn:(UIButton *)btn selected:(BOOL)selected {
//    btn.enabled = enabled;
    
    btn.backgroundColor = selected ? [UIColor lightGrayColor] : [UIColor clearColor];
}

+ (BOOL)checkCampingLightInfo:(SILightInfo *)lightInfo isType:(NSSISceneType)sceneType {
    
    
    NSString *bleName = [SICPSDKService getCurrentBle].identityName;
    NSDictionary *customBleDic = [self userDefaultObjectForKey:bleName];
    NSDictionary *scenesDic = customBleDic[@"scenes_dic"];
    
    BOOL result = NO;
    switch (sceneType) {
        case NSSISceneTypeReading:
            result = [self checkCampingLightInfo:lightInfo isEqualToDic:SMARTIT_READING_SCENE_DIC];
            break;
        case NSSISceneTypeSleeping:
            result = [self checkCampingLightInfo:lightInfo isEqualToDic:SMARTIT_SLEEPING_SCENE_DIC];
            break;
        case NSSISceneTypeScene1:
//            result = scenesDic[SmartITFirstCustomSceneDicKey];
            result = [self checkCampingLightInfo:lightInfo isEqualToDic:scenesDic[SmartITFirstCustomSceneDicKey]];

            //[self checkCampingLightInfo:lightInfo isEqualToDic:[self userDefaultObjectForKey:SmartITFirstCustomSceneDicKey]];
            break;
        case NSSISceneTypeScene2:
//            result = scenesDic[SmartITSecondCustomSceneDicKey];
            result = [self checkCampingLightInfo:lightInfo isEqualToDic:scenesDic[SmartITSecondCustomSceneDicKey]];
            break;
        case NSSISceneTypeSceneCurrent:
//            result = scenesDic[SmartITCurrentSceneDicKey];
            result = [self checkCampingLightInfo:lightInfo isEqualToDic:scenesDic[SmartITCurrentSceneDicKey]];
            break;
        default:
            break;
    }
    return result;
}


+ (BOOL)checkCampingLightInfo:(SILightInfo *)lightInfo isEqualToDic:(NSDictionary *)dic {
    
    if (!dic) {
        return NO;
    }
    
    BOOL isEqual = lightInfo.brightnessValue == [dic[@"brightness_value"] unsignedIntegerValue] &&
                    lightInfo.colorTempValue == [dic[@"color_temp_value"] unsignedIntegerValue] &&
                    lightInfo.mode == [dic[@"mode"] unsignedIntegerValue];
    return isEqual;
}

//+ (void)setUserDefaultObject:(NSObject *)obj forKey:(NSString *)key {
//    [[NSUserDefaults standardUserDefaults] setObject:obj forKey:key];
//}
//
//+ (id)userDefaultObjectForKey:(NSString *)key {
//    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
//}

+ (void)setUserDefaultObject:(NSObject *)obj forKey:(NSString *)key {
    [[NSUserDefaults standardUserDefaults] rm_setCustomObject:obj forKey:key];
}

+ (id)userDefaultObjectForKey:(NSString *)key {
    return [[NSUserDefaults standardUserDefaults] rm_customObjectForKey:key];
}

+ (void)setUserDefaultCampingLightInfo:(SILightInfo *)lightInfo toSceneType:(NSSISceneType)sceneType {
    NSString *sceneTypeKeyStr = @"";
    switch (sceneType) {
        case NSSISceneTypeScene1:
            sceneTypeKeyStr = SmartITFirstCustomSceneDicKey;
            break;
        case NSSISceneTypeScene2:
            sceneTypeKeyStr = SmartITSecondCustomSceneDicKey;
            break;
        case NSSISceneTypeSceneCurrent:
            sceneTypeKeyStr = SmartITCurrentSceneDicKey;
            break;
        default:
            break;
    }
    NSString *bleName = [SICPSDKService getCurrentBle].identityName;
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
                         @(lightInfo.mode), @"mode",
                         @(lightInfo.brightnessValue), @"brightness_value",
                         @(lightInfo.colorTempValue), @"color_temp_value", nil];
    
    NSDictionary *customBleDic = [SIUtil userDefaultObjectForKey:bleName] ? :  [NSDictionary new];
    NSMutableDictionary *muCustomBleDic = [NSMutableDictionary dictionaryWithDictionary:customBleDic];
    NSMutableDictionary *muScenesDic = [NSMutableDictionary dictionaryWithDictionary:customBleDic[@"scenes_dic"]];
    [muScenesDic setObject:dic forKey:sceneTypeKeyStr];
    [muCustomBleDic setObject:muScenesDic forKey:@"scenes_dic"];
//    NSDictionary *resultCustomBleDic = [NSDictionary dictionaryWithDictionary:muScenesDic];
    [SIUtil setUserDefaultObject:muCustomBleDic forKey:bleName];
    
    
    
    
//    NSMutableDictionary *tempSceneDic = [NSMutableDictionary dictionaryWithDictionary:[self userDefaultObjectForKey:bleName]];
//    [tempSceneDic setObject:dic forKey:sceneTypeKeyStr];
//
//    if (!tempSceneDic) {
//        [self setUserDefaultObject:tempSceneDic forKey:bleName];
//    }
//    if (!tempSceneDic) {
//        tempSceneDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:dic, bleName, nil];
//    } else {
//        [tempSceneDic setObject:bleName forKey:dic];
//    }
//    [self setUserDefaultObject:[NSDictionary dictionaryWithDictionary:tempSceneDic] forKey:@"scene_dic"];
//    NSDictionary *sceneDic = [NSDictionary dictionaryWithObjectsAndKeys:dic, bleName, nil];
//
//    [self setUserDefaultObject:dic forKey:sceneTypeKeyStr];
}

+ (SILightInfo *)lightInfoFromSceneType:(NSSISceneType)sceneType currentLightInfo:(SILightInfo *)currentLightInfo {
    NSDictionary *sceneDic = nil;
    NSString *bleName = [SICPSDKService getCurrentBle].identityName;
    NSDictionary *customBleDic = [SIUtil userDefaultObjectForKey:bleName] ? :  [NSDictionary new];
    if (customBleDic) {
        NSDictionary *sceneDics = customBleDic[@"scenes_dic"];
        switch (sceneType) {
            case NSSISceneTypeReading:
                sceneDic = SMARTIT_READING_SCENE_DIC;
                break;
            case NSSISceneTypeSleeping:
                sceneDic = SMARTIT_SLEEPING_SCENE_DIC;
                break;
            case NSSISceneTypeScene1:
                if (sceneDics) {
                    sceneDic = sceneDics[SmartITFirstCustomSceneDicKey];
                }
                //            sceneDic = [SIUtil userDefaultObjectForKey:SmartITFirstCustomSceneDicKey];
                break;
            case NSSISceneTypeScene2:
                if (sceneDics) {
                    sceneDic = sceneDics[SmartITSecondCustomSceneDicKey];
                }
                //            sceneDic = [SIUtil userDefaultObjectForKey:SmartITSecondCustomSceneDicKey];
                break;
            case NSSISceneTypeSceneCurrent:
                if (sceneDics) {
                    sceneDic = sceneDics[SmartITCurrentSceneDicKey];
                }
                //            sceneDic = [SIUtil userDefaultObjectForKey:SmartITCurrentSceneDicKey];
            default:
                break;
        }
    }
    
    SILightInfo *resultLightInfo = [currentLightInfo copy];
    resultLightInfo.mode = [sceneDic[@"mode"] unsignedIntegerValue];
    resultLightInfo.brightnessValue = [sceneDic[@"brightness_value"] unsignedIntegerValue];
    resultLightInfo.colorTempValue = [sceneDic[@"color_temp_value"] unsignedIntegerValue];
    return resultLightInfo;
}

+ (BOOL)sceneExist:(NSSISceneType)sceneType {
    NSDictionary *sceneDic = nil;
    NSString *bleName = [SICPSDKService getCurrentBle].identityName;
    NSDictionary *customBleDic = [SIUtil userDefaultObjectForKey:bleName] ? :  [NSDictionary new];
    NSDictionary *sceneDics = customBleDic[@"scenes_dic"];
    if (!sceneDics) {
        return NO;
    }
    switch (sceneType) {
        case NSSISceneTypeScene1:
            sceneDic = sceneDics[SmartITFirstCustomSceneDicKey];
            break;
        case NSSISceneTypeScene2:
            sceneDic = sceneDics[SmartITSecondCustomSceneDicKey];
            break;
            
        default:
            break;
    }
    return sceneDic != nil;
}

+ (NSString *)convertDateToString:(NSDate *)date withFormatter:(NSString *)formatterStr {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:formatterStr];
    return [formatter stringFromDate:date];
}

+ (NSDate *)convertStringToDate:(NSString *)dateStr withFormatter:(NSString *)formatterStr {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:formatterStr];
    return [formatter dateFromString:dateStr];
}

+ (NSDate *)dateFromHour:(NSUInteger)hour minute:(NSUInteger)minute {
//    if (!hour && !minute) {
//        return nil;
//    }
    NSDate *nowDate = [NSDate date];
    NSString *nowDateString = [self convertDateToString:nowDate withFormatter:SI_YEAR_MONTH_DAY_TIME_FORMATTER];
    NSArray *nowDateArray = [nowDateString componentsSeparatedByString:@":"];
    NSInteger year = [nowDateArray[0] integerValue];
    NSInteger month = [nowDateArray[1] integerValue];
    NSInteger day = [nowDateArray[2] integerValue];
    
    NSDate *date = [self convertStringToDate:[NSString stringWithFormat:@"%lu:%lu:%lu:%lu:%lu", year, month, day, hour, minute]
                    withFormatter:SI_YEAR_MONTH_DAY_HOUR_MINUTE_TIME_FORMATTER];
    return date;
}

+ (NSInteger)hourFromTime:(NSDate *)date {
    if (!date) {
        return 0;
    }
    NSString *hourString = [self convertDateToString:date withFormatter:@"HH"];
    return hourString.integerValue;
}

+ (NSInteger)minuteFromTime:(NSDate *)date {
    if (!date) {
        return 0;
    }
    NSString *hourString = [self convertDateToString:date withFormatter:@"mm"];
    return hourString.integerValue;
}

+ (NSDate *)getDateAfterDay:(NSInteger)day hour:(NSInteger)hour minute:(NSInteger)minute second:(NSInteger)second{
    return [self getDateAfterDate:[NSDate date] day:day hour:hour minute:minute second:second];
}

+ (NSDate *)getDateAfterDate:(NSDate *)date day:(NSInteger)day hour:(NSInteger)hour minute:(NSInteger)minute second:(NSInteger)second {
    NSTimeInterval timeInterval = 24 * 60 * 60 * day + 60 * 60 * hour + 60 * minute + second;
    
    return [NSDate dateWithTimeInterval:(timeInterval) sinceDate:date];
}


+ (NSInteger)minutesBetween:(NSDate *)firstDate and:(NSDate *)secondDate {
    NSTimeInterval interval = [secondDate timeIntervalSinceDate:firstDate];
    return (NSInteger)interval / 60;
     
 }

+ (NSInteger)getPositiveTimeMin:(NSInteger)timeMin {
    
    NSInteger const dayMin = 60 * 12;
    int i = 0;
    while (YES) {
        if (timeMin + i * dayMin >= 0) {
            return timeMin + i * dayMin;
        }
        i ++;
    }
}

+ (NSDate *)getFiveTimesDateFromDate:(NSDate *)date {
    NSTimeInterval interval = (int)[date timeIntervalSince1970] + 1;
    NSInteger interValTimes = interval / 300;
    NSTimeInterval newInterval = (interValTimes + 1) * 300;
    return [NSDate dateWithTimeIntervalSince1970:newInterval];
}

+ (BOOL)stringArray:(NSArray<NSString *>*)strArray containsString:(NSString *)str matching:(BOOL)matching {
    for (NSString *subStr in strArray) {
        BOOL condition = NO;
        if (matching) {
            condition = [str isEqualToString:subStr];
        } else {
            condition = [self checkString:subStr containSubString:str];
        }
        if (condition) {
            return YES;
        }
    }
    return NO;
}

+ (NSInteger)stringArray:(NSArray<NSString *>*)strArray indexOfString:(NSString *)str {
    for (NSString *subStr in strArray) {
        BOOL condition = NO;
        condition = [str isEqualToString:subStr];
        if (condition) {
            return [strArray indexOfObject:subStr];
        }
    }
    return -1;

}

+ (void)setHistoryPeripheralNameToUserDefault:(NSString *)peripheralName {
    [self setUserDefaultObject:peripheralName forKey:SmartITHistoryLightNameKey];
}

+ (void)addBottomBorderToTextField:(UITextField *)textField leftViewText:(NSString *)leftViewText {
    
    CALayer *border = [CALayer layer];
    CGFloat borderWidth = .5f;
    border.borderColor = [UIColor lightGrayColor].CGColor;
    border.frame = CGRectMake(0, textField.frame.size.height - borderWidth, textField.frame.size.width, textField.frame.size.height);
    border.borderWidth = borderWidth;
    [textField.layer addSublayer:border];
    textField.layer.masksToBounds = YES;
    
    if ([SIUtil checkStringExist:leftViewText]) {
        UILabel *textFieldLeftLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30.f, 30.f)];
        textFieldLeftLabel.backgroundColor = [UIColor clearColor];
        textFieldLeftLabel.textAlignment = NSTextAlignmentCenter;
        textFieldLeftLabel.font = [UIFont systemFontOfSize:17.f];
        textFieldLeftLabel.text = leftViewText;
        [textFieldLeftLabel sizeToFit];
        [textFieldLeftLabel si_resetWithDeltaX:0 deltaY:0 deltaWidth:8.f deltaHeight:0];
        textFieldLeftLabel.textColor = [UIColor lightGrayColor];
        textField.leftViewMode = UITextFieldViewModeAlways;
        textField.leftView = textFieldLeftLabel;
    }
}

//将十进制转化为二进制,设置返回NSString 长度

+ (NSString *)decimalToBinary:(uint16_t)tmpid backLength:(int)length
{
    NSString *a = @"";
    while (tmpid)
    {
        a = [[NSString stringWithFormat:@"%d",tmpid%2] stringByAppendingString:a];
        if (tmpid/2 < 1)
        {
            break;
        }
        tmpid = tmpid/2 ;
    }
    
    if (a.length <= length)
    {
        NSMutableString *b = [[NSMutableString alloc]init];;
        for (int i = 0; i < length - a.length; i++)
        {
            [b appendString:@"0"];
        }
        
        a = [b stringByAppendingString:a];
    }
    
    return a;
    
}

+ (NSString *)stringOfEndIndex:(NSInteger)index totalString:(NSString *)totalString {
    
    if (index >= totalString.length) {
        return @"";
    }
    return [totalString substringWithRange:NSMakeRange(totalString.length - 1 - index, 1)];
}

+ (BOOL)isAtMainThread {
    if (strcmp(dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL), dispatch_queue_get_label(dispatch_get_main_queue())) == 0) {
        // do something  in main thread
        return YES;
    } else {
        // do something in other thread
        return NO;
    }
}

+ (NSString *)identityVersion {
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
}

+ (void)resetAllDefaults {
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    NSDictionary * dict = [defs dictionaryRepresentation];
    for (id key in dict.allKeys) {
        if ([key isKindOfClass:[NSString class]]) {
            [defs removeObjectForKey:key];
        }
    }
    [defs synchronize];
}

+ (void)setSuperView:(UIView *)superView fromLastSubView:(UIView *)lastSubView spacing:(CGFloat)spacing {
    CGRect superViewFrame = superView.frame;
    CGRect lastSubViewFrame = lastSubView.frame;
    //    if (CGRectGetMaxY(lastSubViewFrame) + spacing > superViewFrame.size.height) {
    superViewFrame.size.height = CGRectGetMaxY(lastSubViewFrame) + spacing;
    //    }
    superView.frame = superViewFrame;
}
@end
